package cn.king.user.service.impl;

import cn.king.basic.exception.BusinessException;
import cn.king.basic.util.Md5Utils;
import cn.king.basic.util.StrUtils;
import cn.king.user.domain.Logininfo;
import cn.king.user.domain.User;
import cn.king.user.mapper.LogininfoMapper;
import cn.king.user.mapper.UserMapper;
import cn.king.user.service.IUserService;
import cn.king.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");
        //空值校验
        if (StringUtils.isEmpty(phone)){
            throw new BusinessException("电话号码不能为空！");
        }
        if (StringUtils.isEmpty(phoneCode)){
            throw new BusinessException("验证码不能为空！");
        }
        if (StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd)){
            throw new BusinessException("密码不能为空！");
        }
        //判断两次密码是否一致
        if (!pwd.equals(rePwd)){
            throw new BusinessException("两次密码不一致，请重新输入！");
        }
        //手机验证码是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if (obj == null){
            throw new BusinessException("验证码已过期，请重新获取！");
        }
        //redis中手机验证码的储存格式：【业务键：电话号码 - 手机验证码：时间戳】
        if (!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("验证码错误，请核对后重新输入！");
        }

        //添加到数据库
        //当将一个对象转为另一个对象的时候，并且代码量很多就用 Obj2Obj格式命名
        User user = map2User(map);
        Logininfo logininfo = user2loginInfo(user);
        //先添加t_loginInfo
        logininfoMapper.add(logininfo);
        //再添加t_user
        user.setLogininfoId(logininfo.getId()); //添加loginInfo的id
        userMapper.add(user);
    }

    /**
     * 邮箱注册
     */
    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");
        //空值判断
        if (StringUtils.isEmpty(email)){
            throw new BusinessException("邮箱账号不能为空！");
        }
        if (StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd)){
            throw new BusinessException("密码不能为空！");
        }
        //判断邮箱格式是否正确
        String format = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$";
        if (!email.matches(format)){
            throw new BusinessException("邮箱格式有误！");
        }
        //判断邮箱是否已经注册
        User userEmail = userMapper.getByEmail(email);
        if (userEmail != null){
            throw new BusinessException("该邮箱已注册，请核对信息！");
        }
        //判断两次密码是否一致
        if (!pwd.equals(rePwd)) {
            throw new BusinessException("两次密码不一致，请重新输入！");
        }

        //注册成功：将数据添加到数据库
        //当将一个对象转为另一个对象的时候，并且代码量很多就用 Obj2Obj格式命名
        User user = emailMap2User(map);
        Logininfo logininfo = emailUser2loginInfo(user);
        //先添加t_loginInfo
        logininfoMapper.add(logininfo);
        //再添加t_user
        user.setLogininfoId(logininfo.getId()); //添加loginInfo的id
        userMapper.add(user);

        //发送激活邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("2097862548@qq.com");
        helper.setSubject("店铺激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>恭喜你注册成功，赶快激活吧！    ————【强盛集团】</h1>" +
                "<a href='http://172.16.6.251:8080/user/active/"+user.getId()+"'>点击该链接激活</a>",true);
        //收件人
        helper.setTo(email);
        javaMailSender.send(mimeMessage);
    }

    /**
     * 激活邮件
     */
    @Override
    public void active(Long id) {
        userMapper.updateState(1,id);
    }

    /**
     * 邮箱注册添加到登录信息数据库
     */
    private Logininfo emailUser2loginInfo(User user) {
        Logininfo logininfo = new Logininfo();
        //使用BeanUtils.copyProperties方法，将对象中同名的属性内容拷贝到另一个对象中
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1); // 1 是用户， 0 是管理员
        logininfo.setDisable(true);
        return logininfo;
    }

    /**
     * 邮箱注册添加到用户数据库
     */
    private User emailMap2User(Map<String, String> map) {
        User user = new User();
        //先获取前端传入的邮箱
        String email = map.get("email");
        //在添加到user中
        user.setUsername(email);
        user.setEmail(email);
        //调用工具类生成32位随机的 盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密再加盐
        String pwd = Md5Utils.encrypByMd5(map.get("pwd") + salt);
        user.setSalt(salt);
        user.setPassword(pwd);
        //刚刚注册的状态应该为禁用
        user.setState(0);
        return user;
    }

    /**
     * 电话号码注册添加到登录信息数据库
     */
    private Logininfo user2loginInfo(User user) {
        Logininfo logininfo = new Logininfo();
        //使用BeanUtils.copyProperties方法，将对象中同名的属性内容拷贝到另一个对象中
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1); // 1 是用户， 0 是管理员
        logininfo.setDisable(true);
        return logininfo;
    }

    /**
     * 电话号码注册添加到用户数据库
     */
    private User map2User(Map<String, String> map) {
        User user = new User();
        //先获取前端传入的电话号码
        String phone = map.get("phone");
        //在添加到user中
        user.setUsername(phone);
        user.setPhone(phone);
        //调用工具类生成32位随机的 盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密再加盐
        String pwd = Md5Utils.encrypByMd5(map.get("pwd") + salt);
        user.setSalt(salt);
        user.setPassword(pwd);
        user.setState(1);
        return user;
    }

    @Override
    @Transactional
    public void add(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        //先查询登陆信息id
        User user = userMapper.getOne(id);

        //删除user
        super.delete(id);

        //删除logininfo
        logininfoMapper.delete(user.getLogininfoId());
    }

    @Override
    @Transactional
    public void update(User user) {//前端传过来的user是没有登陆信息id
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.getOne(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.getOne(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }
}
